package com.elitel.frame.main.security;

import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.*;

/**
 * TODO: JWT Token 工具
 *
 * @since 2020-02-19
 */
@Component
@ConfigurationProperties(prefix = "authorize")
public class JwtTokenUtil implements Serializable {
    private static final long serialVersionUID = 1924305428324381392L;
    // JWT Token 授权私钥
    private String privateSecret;

    // 授权 Token 过期时间
    private int expirationS;

    // 授权类型
    private String type;

    public String getPrivateSecret() {
        return privateSecret;
    }

    public void setPrivateSecret(String privateSecret) {
        this.privateSecret = privateSecret;
    }

    public int getExpirationS() {
        return expirationS;
    }

    public void setExpirationS(int expirationS) {
        this.expirationS = expirationS;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    /**
     * TODO: 根据数据值生成授权 Token
     *
     * @param claims
     * @param name
     * @return
     */
    public String generateToken(Map<String, Object> claims, String name) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, expirationS);

        String token =
                Jwts.builder()
                        .setClaims(claims)
                        .setId(UUID.randomUUID().toString())
                        .setSubject(name)
                        //设置token过期时间
                        .setExpiration(calendar.getTime())
                        //使用HMAC-SHA256算法和授权私钥，生成一个token
                        .signWith(SignatureAlgorithm.HS256, privateSecret)
                        .compact();
        return token;
    }

    /**
     * TODO: 生成令牌
     *
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put("created", new Date());
        return generateToken(claims, userDetails.getUsername());
    }

    /**
     * TODO: 从token令牌中获取数据声明
     *
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token) throws ExpiredJwtException {
        JwtParser parser = Jwts.parser().setSigningKey(privateSecret);
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
//    return Jwts.parser().setSigningKey(privateSecret).parseClaimsJws(token).getBody();
    }
}
